package com.simplehire.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DeepSeekService implements AIService {  // 实现AIService接口

    private static final Logger logger = LoggerFactory.getLogger(DeepSeekService.class);

    @Value("${deepseek.api.key}")
    private String apiKey;

    private final WebClient webClient;
    private final ObjectMapper objectMapper;

    public DeepSeekService(WebClient.Builder webClientBuilder, ObjectMapper objectMapper) {
        this.webClient = webClientBuilder
                .baseUrl("https://api.deepseek.com/v1")
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .build();
        this.objectMapper = objectMapper;
    }

    @Override
    public String analyzeResume(String resumeText) {
        logger.info("开始分析简历，文本长度: {}", resumeText.length());
        String prompt = String.format("""
            你是一位专业的 HR 面试官，现在我要面试一个候选人，你现在帮助我面试，请基于以下简历内容：
            
            %s
            
            请完成以下任务：
            1. 生成 3 个与该简历相关的面试问题；
            2. 模拟面试并给出综合评分（满分 100 分）；
            3. 提供至少 3 条简历优化建议。
            
            请直接以清晰的中文格式返回结果，不需要JSON格式。
            """, resumeText);

        return callDeepSeekAPI(prompt);
    }

    @Override
    public String continueConversation(String resumeText, String conversationHistory, String userMessage) {
        logger.info("继续对话，用户消息: {}", userMessage);

        // 构建完整的对话上下文
        List<Map<String, String>> messages = new ArrayList<>();

        // 系统提示词
        messages.add(Map.of(
                "role", "system",
                "content", "你是一位专业的HR面试官，正在辅助我面试一位候选人。请根据候选人的简历内容帮助我进行专业的面试对话。保持友好但专业的态度，可以提问、给出反馈或建议。"
        ));

        // 简历内容
        messages.add(Map.of(
                "role", "system",
                "content", "候选人简历内容：\n" + resumeText
        ));

        // 解析对话历史（兼容多模型格式）
        if (conversationHistory != null && !conversationHistory.trim().isEmpty()) {
            logger.debug("对话历史长度: {}", conversationHistory.length());
            String[] lines = conversationHistory.split("\n\n");
            for (String line : lines) {
                // 支持多种模型的历史格式（如"deepseek面试辅助:"、"doubao面试辅助:"等）
                if (line.startsWith("我:")) {
                    String content = line.substring(2).trim();  // 提取"我: "后的内容
                    messages.add(Map.of("role", "user", "content", content));
                } else if (line.contains("面试辅助:")) {
                    int colonIndex = line.indexOf(":");
                    if (colonIndex > 0) {
                        String content = line.substring(colonIndex + 1).trim();
                        messages.add(Map.of("role", "assistant", "content", content));
                    }
                }
            }
        }

        // 添加当前用户消息
        messages.add(Map.of("role", "user", "content", userMessage));

        logger.debug("发送给API的消息数量: {}", messages.size());
        return callDeepSeekAPIMulti(messages);
    }

    @Override
    public String getModelName() {
        return "deepseek";  // 实现接口方法，返回模型名称
    }

    private String callDeepSeekAPIMulti(List<Map<String, String>> messages) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "deepseek-chat");
        requestBody.put("messages", messages);
        requestBody.put("temperature", 0.7);
        requestBody.put("max_tokens", 2000);

        logger.debug("准备调用DeepSeek API，模型: deepseek-chat");
        return callAPI(requestBody);
    }

    private String callDeepSeekAPI(String prompt) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "deepseek-chat");
        requestBody.put("messages", new Object[]{
                Map.of("role", "user", "content", prompt)
        });
        requestBody.put("temperature", 0.7);
        requestBody.put("max_tokens", 2000);

        logger.debug("准备调用DeepSeek API，提示长度: {}", prompt.length());
        return callAPI(requestBody);
    }

    private String callAPI(Map<String, Object> requestBody) {
        try {
            logger.debug("API密钥: {}", apiKey != null ? "已设置" : "未设置");

            String response = webClient.post()
                    .uri("/chat/completions")
                    .header(HttpHeaders.AUTHORIZATION, "Bearer " + apiKey)
                    .bodyValue(requestBody)
                    .retrieve()
                    .onStatus(status -> status.isError(), clientResponse -> {
                        logger.error("API调用失败，状态码: {}", clientResponse.statusCode());
                        return clientResponse.bodyToMono(String.class)
                                .flatMap(errorBody -> {
                                    logger.error("API错误响应: {}", errorBody);
                                    return Mono.error(new RuntimeException("API调用失败: " + clientResponse.statusCode() + " - " + errorBody));
                                });
                    })
                    .bodyToMono(String.class)
                    .block();

            logger.debug("API原始响应: {}", response);
            return parseAPIResponse(response);

        } catch (Exception e) {
            logger.error("调用AI服务失败", e);
            return "网络错误，请检查API密钥和网络连接: " + e.getMessage();
        }
    }

    private String parseAPIResponse(String response) {
        try {
            if (response == null || response.trim().isEmpty()) {
                logger.error("API响应为空");
                return "API响应为空，请检查网络连接";
            }

            JsonNode rootNode = objectMapper.readTree(response);
            logger.debug("解析后的JSON: {}", rootNode.toString());

            // 检查是否有错误
            if (rootNode.has("error")) {
                JsonNode errorNode = rootNode.path("error");
                String errorMessage = errorNode.path("message").asText("未知错误");
                logger.error("API返回错误: {}", errorMessage);
                return "API错误: " + errorMessage;
            }

            JsonNode choices = rootNode.path("choices");
            logger.debug("Choices数组长度: {}", choices.size());

            if (choices.isArray() && choices.size() > 0) {
                JsonNode firstChoice = choices.get(0);
                JsonNode message = firstChoice.path("message");

                if (message.has("content")) {
                    String content = message.get("content").asText();
                    logger.debug("成功解析AI响应，内容长度: {}", content.length());
                    return content;
                } else {
                    logger.error("消息中没有content字段: {}", message.toString());
                }
            } else {
                logger.error("没有choices或choices为空: {}", choices.toString());
            }

            // 尝试其他可能的响应格式
            if (rootNode.has("message")) {
                String message = rootNode.path("message").asText();
                logger.debug("使用message字段: {}", message);
                return message;
            }

            logger.error("未能解析AI响应，原始响应: {}", response);
            return "未能解析AI响应，请检查API配置。响应格式: " + rootNode.toString();

        } catch (Exception e) {
            logger.error("解析AI响应失败", e);
            return "解析AI响应失败: " + e.getMessage() + "。原始响应: " + response;
        }
    }

    // 测试连接方法
    public String testConnection() {
        try {
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "deepseek-chat");
            requestBody.put("messages", new Object[]{
                    Map.of("role", "user", "content", "你好，请回复'连接成功'")
            });
            requestBody.put("max_tokens", 50);

            String response = callAPI(requestBody);
            logger.info("测试连接结果: {}", response);
            return response;
        } catch (Exception e) {
            return "测试失败: " + e.getMessage();
        }
    }

    public String getApiKey() {
        return apiKey;
    }
}